<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-12-17
 * Time: 8:43
 */


namespace app\common\model;

use app\common\service\AddService;
use think\Db;
use think\Model as ThinkModel;
use app\common\service\OrdinaryService;
use app\common\service\ReceiverService;
use app\common\model\HandCard as HandCardM;
//项目表
class Orderproject extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'qt_order_project';
    protected $pk = 'id';
    protected $autoWriteTimestamp = true;

    // 订单商品
    public function orderqueue()
    {
        return $this->hasOne('Orderqueue', 'order_project_id', 'id');
    }

    //项目详情
    public function getproject()
    {
        return $this->hasOne('Project', 'project_id', 'id');
    }

    /**
     * @param $store_id
     * @param $roomid
     * @param $engineer_id
     * @param $limit
     * @return array
     * 获取当前房间指定技师的项目
     */
    public function getRoomProject($store_id, $roomid, $engineer_id)
    {
        $type = ['1' => '轮排', '2' => '点钟', '3' => 'call钟', '4' => '优钟', '5' => '加钟'];
        //1未开始 2 已上钟 3 已结束  4 换技师（终止）  5 换项
        $status = ['1' => '未开始', '2' => '已上钟', '3' => '已结束 ', '4' => '换技师', '5' => '换项'];
        $where = [];
        if (empty($roomid)) {
            return [];
        }
        if (!empty($engineer_id)) {
            $where[] = ['engineer_id', 'eq', $engineer_id];
        }
        $where[] = ['store_id', 'eq', $store_id];
        $where[] = ['is_delete', 'eq', '2'];
        $where[] = ['is_change', 'eq', '1'];
        $list = $this
            ->where($where)
            ->where('status', '<', '3')
            ->order('created_time', 'asc')
            ->paginate()
            ->each(function ($item) use ($type, $status) {
                $item['order_type_name'] = $type[$item['order_type']];
                $item['hand_card_name'] = Db::name('qt_hand_card')->where(['id'=>$item['hand_card_id']])->value('name');
                $item['create_time'] = ST($item['create_time']);
                $item['status_name'] = $status[$item['status']];
                $item['cha'] = $item['end_time'] == '' ? '0' : $item['end_time'] - time();
                $item['end_time'] = $item['end_time'] == '' ? '' : ST($item['end_time']);
                $item['start_time'] = $item['start_time'] == '' ? '' : ST($item['start_time']);
                return $item;
            });

        return $list->items();
    }


    /**
     * @param $store_id
     * @param $roomid
     * @param $engineer_id
     * @param $limit
     * @return array
     * 获取当前房间指定技师的项目
     */
    public function getChangeProject($store_id, $roomid, $engineer_id)
    {
        $type = ['1' => '轮排', '2' => '点钟', '3' => 'call种', '4' => '优钟', '5' => '加钟'];
        //1未开始 2 已上钟 3 已结束  4 换技师（终止）  5 换项
        $status = ['1' => '未开始', '2' => '已上钟', '3' => '已结束 ', '4' => '换技师', '5' => '换项'];
        $where = [];
        if (empty($roomid)) {
            return [];
        }
        if (!empty($engineer_id)) {
            $where[] = ['engineer_id', 'eq', $engineer_id];
        }
        $where[] = ['room_id', 'eq', $roomid];
        $where[] = ['store_id', 'eq', $store_id];
        $project = new Project();
        $list = $this
            ->where($where)
            ->where('status', '<', '3')
            ->order('created_time', 'desc')
            ->paginate()
            ->each(function ($item) use ($type, $status, $project) {
                $item['order_type_name'] = $type[$item['order_type']];
                $item['create_time'] = ST($item['create_time']);
                $item['status_name'] = $status[$item['status']];
                //$item['project_info']=$project->getProjectInfo($item['store_id'],$item['project_id']);
                $item['cha'] = $item['end_time'] == '' ? '0' : $item['end_time'] - time();
                $item['end_time'] = $item['end_time'] == '' ? '' : ST($item['end_time']);
                $item['start_time'] = $item['start_time'] == '' ? '' : ST($item['start_time']);
                return $item;
            });

        return $list->items();
    }

    /**
     * @param $id
     * @param $engineer_id
     * @param $type 1 上钟 2 下钟
     * @return array
     * 上下钟
     */
    public function start_project($id, $engineer_id, $type,$userInfo = [])
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
        $order_project = $this->where('id', $id)->find();
        if (empty($order_project)) {
            $result['msg'] = '项目不存在';
            return $result;
        }
        $project = Project::where('id', $order_project['project_id'])->find();
        $time = $project['time'] * 60;
        if ($type == '1') {
            //判断是否有组合下单
            $roomType = Db::name('qt_room')->where(['id'=>$order_project['room_id']])->value('type_id');
            $combine = Db::name('qt_data_combine')
                ->where(['project_id'=>$order_project['project_id']])
                ->where("FIND_IN_SET(" . $order_project['order_type'] . ",block_type)")
                ->where("FIND_IN_SET(" . $roomType . ",room_type)")
                ->find();
            if(!empty($combine)){
                $goodsPost = Db::name('qt_data_combine_goods')
                    ->field('com.goods_id as product_id,com.number as num,g.name as product_name,g.price as product_price')
                    ->alias('com')
                    ->leftJoin('qt_goods g','g.id = com.goods_id')
                    ->where(['com.combine_id'=>$combine['id']])->select();
                $totalPrice = 0;
                foreach ($goodsPost as $key=>$value){
                    $goodsPost[$key]['goods_total_price'] = bcmul($value['num'],$value['product_price']);
                    $totalPrice += $goodsPost[$key]['goods_total_price'];
                }
                $data['goods'] = json_encode($goodsPost);
                $data['hand_card_id'] = $order_project['hand_card_id'];
                $data['engineer_id'] = $order_project['sale_id'];
                $data['total_price'] = $totalPrice;
                $data['room_id'] = $order_project['room_id'];
                $data['content'] = '';
                //商品下单
                $orderModel = new ProductOrder();
                $order_data = $orderModel->createOrder($data, $userInfo);
                if ($order_data['status'] == true) {
                    //插入消息
                    $goodsData = json_decode($data['goods'],true);
                    goodsOrderMessage($userInfo['store_id'],$goodsData,$order_project['room_id']);
                }else{
                    $result['status'] = false;
                    $result['msg'] = '组合下单出错了';
                    return $result;
                }
            }
            $start_time = time();
            Db::startTrans();
            try {
                //更新项目订单状态
                Db::name('qt_order_project')->where('id', $id)->update(['start_time'=>$start_time,'end_time'=>$start_time + $time,'status'=>2]);
                //处理段位费
                $duanwei = Db::name('qt_duanwei')->where(['project_id'=>$order_project['project_id'],'engineer_id'=>$engineer_id])->find();
                if(!empty($duanwei)){
                    if($order_project['hand_card_id'] != null){
                        //给段位费增加手牌
                        $goodsOrder = Db::name('qt_product_order_item')
                            ->where(['goods_id'=>$duanwei['product_id'],'business_type'=>'5','pay_status'=>'0','status'=>'1'])->find();
                        Db::name('qt_product_order_item')->where(['id'=>$goodsOrder['id']])->update(['hand_card_id'=>$order_project['hand_card_id']]);
                        //手牌增加金额
                        HandCardM::incHandCardMoney($goodsOrder['id'],$order_project['hand_card_id'],'2');
                    }
                }
                //更新房间状态
                Db::name('qt_room')->where('id', $order_project['room_id'])->update(['status_id'=>'3']);
                //更新技师状态
                Db::name('qt_users')->where('id', $engineer_id)->update(['work_status'=>'4']);
                DB::name('qt_order_queue')->where('order_project_id', $id)->where('user_id', $engineer_id)->update(['start_time'=>$start_time,'end_time'=>$start_time + $time,'status'=>3]);
                Db::commit();
                $res = true;
            } catch (\Exception $e) {
                Db::rollback();
                $res = false;
            }
            if ($res) {
                $result['status'] = true;
                return $result;
            } else {
                $result['msg'] = $e->getMessage();
                return $result;
            }
        } else {
            //下钟
            //判断当前房间是否还有技师
            $engineerCount = Db::name('qt_order_queue')->where(['room_id' => $order_project['room_id']])->count();
            $storeInfo = Db::name('qt_store')->where('id', $order_project['store_id'])->find();
            //如果没有，更新房间状态
            if ($engineerCount <= 1) {
                //项目
                $project = Db::name('qt_order')
                    ->field('o.*')
                    ->alias('o')
                    ->leftJoin('qt_room r', 'r.id = o.room_id')
                    ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                    ->where(['o.id' => $order_project['order_id']])
                    ->order('o.id desc')
                    ->find();
                $projectRes = Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,room_id,hand_card_id')
                    ->whereIn('order_id', $project)
                    ->where('is_change', '1')
                    ->where('is_delete',2)
                    ->select();
                //商品
                $goods = Db::name('qt_product_order')
                    ->field('o.id,r.name as room_name,h.name as hand_card_name,engineer_id')
                    ->alias('o')
                    ->leftJoin('qt_room r', 'r.id = o.room_id')
                    ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                    ->whereIn('room_id', $order_project['room_id'])
                    ->column('o.id');
                $productRes = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price')
                    ->whereIn('order_id', $goods)
                    ->where('pay_status', '0')
                    ->select();
                $room['status_id'] = 4;
                //如果房间里面没有未结账的项目和商品
                if (empty($projectRes) && empty($productRes)) {
                    //自动脏房
                    if ($storeInfo['is_auto_dirty_room'] == '1') {
                        $room['status_id'] = 5;
                    } else {
                        $room['status_id'] = 4;
                        $room['down_time'] = time();
                    }
                } else {
                    $room['down_time'] = time();
                }
            } else {
                $endEngineer = Db::name('qt_order_queue')->where(['room_id' => $order_project['room_id']])->find();
                if ($endEngineer['status'] == '2') {
                    $room['status_id'] = '2';
                } elseif ($endEngineer['status'] == '3') {
                    $room['status_id'] = '3';
                } else {
                    $room['status_id'] = '10';
                }

            }
            $update['real_end_time'] = time();
            $update['status'] = 3;
            $engineer['work_status'] = '1';
            //更新技师排钟信息
            $que['real_time'] = time();
            $que['status'] = 1;
            $que['room_id'] = null;
            $que['project_id'] = null;
            $que['order_project_id'] = null;
            $que['order_user_id'] = null;
            $que['start_time'] = null;
            $que['end_time'] = null;
            //查找该技师的所有项目
            $engineerProjectIds = Db::name('qt_order_project')
                ->where('is_delete',2)
                ->where(['room_id'=>$order_project['room_id'],'engineer_id'=>$engineer_id,'order_id'=>$order_project['order_id']])
                ->column('id');
            Db::startTrans();
            try {
                //更新项目订单状态
                foreach ($engineerProjectIds as $key=>$value){
                    Db::name('qt_order_project')->where('id', $value)->update($update);
                }
                //更新房间状态
                Db::name('qt_room')->where('id', $order_project['room_id'])->update($room);
                //更新技师状态
                Db::name('qt_users')->where('id', $engineer_id)->update($engineer);
                DB::name('qt_order_queue')->where('user_id', $engineer_id)->update($que);
                Db::commit();
                $res = true;
            } catch (\Exception $e) {
                Db::rollback();
                $res = false;
            }
            //安排等位
            $waitRes = Db::name('qt_wait')
                ->where(['store_id' => $storeInfo['id'], 'status' => '1','delay_time'=>'0'])
                ->where('room_id', 'neq', $order_project['room_id'])
                ->order('is_first desc id desc')
                ->find();
            if (!empty($waitRes)) {
                //查找可以安排的技师
                $data['man_num'] = 0;
                $data['woman_num'] = 0;
                $data['other_num'] = 0;
                if($waitRes['sex'] == '1'){
                    $data['man_num'] = $waitRes['number'];
                }
                if($waitRes['sex'] == '2'){
                    $data['woman_num'] = $waitRes['number'];
                }
                if($waitRes['sex'] == '3'){
                    $data['other_num'] = $waitRes['number'];
                }
                $data['project_id'] = $waitRes['project_id'];
                $data['room_id'] = $waitRes['room_id'];
                $data['hand_card_id'] = '';
                $data['delay']= 0;
                $data['time_type'] = 1;
                $data['order_type'] = 1;
                $data['sale_id'] = $waitRes['engineer_id']?? 0;
                $data['creater_room'] = $waitRes['create_id']?? 0;
                $data['create_id'] = $userInfo['id']?? '';
                $orderModel = new \app\common\model\Order();
                $code = $orderModel->create_order($data,$userInfo);
                if($code['code'] == '200'){
                    Db::name('qt_wait')->where(['id' => $waitRes['id']])->update(['status' => '2']);
                }
            }
            if ($res) {
                $result['status'] = true;
                return $result;
            } else {
                $result['msg'] = $e->getMessage();
                return $result;
            }
        }
    }

    /**
     * @param $store_id
     * @param $roomid
     * @param $engineer_id
     * @param $limit
     * @return array
     * 获取当前房间指定技师的项目
     */
    public function get_all_project($store_id, $roomid, $order_id)
    {
        $type = ['1' => '轮排', '2' => '点钟', '3' => 'call种', '4' => '优钟', '5' => '加钟'];
        $status = ['1' => '空闲中', '2' => '服务中', '3' => '已结束', '4' => '换技师'];
        $where = [];
        if (empty($roomid)) {
            return false;
        }
        $where[] = ['room_id', 'eq', $roomid];
        $where[] = ['store_id', 'eq', $store_id];
        $project = new Project();
        $list = $this
            ->field('id,name,price,room_id,engineer_id,order_id')
            ->where($where)
            ->where('status', '<=', '3')
            ->where('order_id', $order_id)
            ->order('created_time', 'asc')
            ->paginate()
            ->each(function ($item) {
                $item['room_name'] = Room::where('id', $item['room_id'])->value('name');
                $item['work_number'] = Users::where('id', $item['engineer_id'])->value('work_number');
                return $item;
            });

        return $list->items();
    }

    /**
     *  项目详情
     * @param int $store_id 门店ID
     * @param int $project_id 项目ID
     **/
    public function getProjectInfo($store_id = 0, $project_id)
    {
        $where[] = ['id', 'eq', $project_id];
        if (!empty($store_id)) {
            $where[] = ['store_id', 'eq', $store_id];
        }
        $info = $this->where('id', $project_id)->find();
        if ($info) {
            $info['images'] = get_album_array_path($info['images']);
        }

        return $info;
    }

    /**
     *  换技师
     * @param int $store_id 门店ID
     * @param int $project_id 项目ID
     **/
    public function change_engineer($store_id = 0, $project_id, $room_id, $sex = '1', $engineer_id)
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
        $now = Db::name('qt_order_queue')
            ->where('user_id', $engineer_id)
            //->where('day',date('Y-m-d'))
            ->find();
        if (empty($now) || $now['order_project_id'] == '0') {
            $result['msg'] = '当前项目不存在';
            return $result;
        }
        $nowproject = $this->where('id', $now['order_project_id'])->find();
        if (empty($nowproject)) {
            $result['msg'] = '项目订单不存在';
            return $result;
        }
//        if(time()-$nowproject['start_time']>=10*60){
//            $result['msg']='超过十分钟无法更换技师';
//            return $result;
//        }
        $project['order_id'] = $nowproject->order_id;
        $project['room_id'] = $room_id;
        $project['hand_card_id'] = $nowproject->hand_card_id;
        $project['order_type'] = '1';
        $project['status'] = '1';
        $project['project_id'] = $project_id;
        $project['store_id'] = $nowproject->store_id;
        $project['name'] = $nowproject->name;
        $project['price'] = $nowproject->price;
        $project['payment_price'] = $nowproject->price;
        $project['created_time'] = time();
        $project['is_change'] = '3';
        Db::startTrans();
        try {
            Db::name('qt_order_project')
                ->where('is_delete',2)->where('id', $now['order_project_id'])->update(['status' => '4']);
            //删除提成记录
            Db::name('qt_commission_log')->where(['order_project_id'=>$now['order_project_id'],'type'=>'1'])->delete();
            $neworder_project_id = Db::name('qt_order_project')->insertGetId($project);
            $l = $this->find_engineer($now['order_project_id'], $now['project_id'], $sex, $neworder_project_id, '1');
            if ($l['status']) {
                Db::commit();
                $res = true;
            } else {
                Db::rollback();
                $result = $l;
                $res = false;
            }
        } catch (\Exception $e) {
            Db::rollback();
            $res = false;
            $result['msg'] = $e->getMessage();
        }
        if ($res) {
            $result['status'] = true;
        } else {
            return $result;
        }

    }

    /**
     * 加钟
     * @param int $store_id 门店ID
     * @param int $project_id 项目ID
     **/
    public function add_project($store_id = 0, $project_id, $room_id)
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
        $room = Room::where('id', $room_id)->find();
        $order_id = $room['order_id'];
        $bigorder = Order::where('id', $order_id)->find();
        $nowproject = Project::where('id', $project_id)->find();
        if (empty($nowproject)) {
            $result['msg'] = '当前项目不存在';
            return $result;
        }
        $find = Db::name('qt_order_queue')
            ->where(['user_id' => $bigorder['engineer_id']])
            ->find();
        $orderProject = Db::name('qt_order_project')
            ->where('is_delete',2)->where('id', $find['order_project_id'])->find();
        $project['order_id'] = $order_id;
        $project['room_id'] = $room_id;
        $project['hand_card_id'] = $bigorder['hand_card_id'];
        $project['order_type'] = '5';
        $project['status'] = '1';
        $project['project_id'] = $project_id;
        $project['store_id'] = $store_id;
        $project['name'] = $nowproject['name'];
        $project['price'] = $nowproject['add_block_price'];
        $project['payment_price'] = $nowproject['add_block_price'];
        $project['created_time'] = time();
        $project['is_change'] = '1';
        $project['is_add'] = '2';
        $project['start_time'] = time();
        $project['end_time'] = $orderProject['end_time'] + ($project['add_block_time'] * 60);
        $rale = $nowproject['add_block_rate'];
        //新增订单提成明细表  暂时未加
        $commion_log = array(
            'store_id' => $store_id,
            'user_id' => $orderProject['engineer_id'],
            //'cashier_id'=>$arr['saler_id'],
            'member' => $bigorder['uv_id'],
            'money' => $nowproject['add_block_price'],
            'payment_price' => $nowproject['add_block_price'],
            'commission' => $nowproject['add_block_price'] * $rale / 100,
            'rale' => $rale,
            'product_id' => $project_id,
            'type' => '1',
            'pay_type' => '',
            'created_time' => time(),
            'room_id' => $room_id,
            'is_pay' => '1',
        );

        Db::startTrans();
        try {
            $neworder_project_id = Db::name('qt_order_project')->insertGetId($project);
            CommissionLog::create($commion_log);
            //修改新的技师
            Db::name('qt_order_queue')->where('id', $orderProject['engineer_id'])->update(
                [
                    'room_id' => $room_id,
                    'project_id' => $project_id,
                    'order_project_id' => $neworder_project_id,
                    'order_user_id' => $bigorder['uv_id'],
                    'status' => '2',
                    'end_time' => $orderProject['end_time'] + ($project['add_block_time'] * 60)
                ]
            );
            Db::commit();
            $res = true;
        } catch (\Exception $e) {
            Db::rollback();
            $res = false;
        }
        if ($res) {
            $result['status'] = true;
            return $result;
        } else {
            $result['msg'] = $e->getMessage();
            return $result;
        }

    }

    /**
     * @param $old_order_project_id //旧的分订单id
     * @param $project_id // 项目id
     * @param string $sex //性别
     * @param string $new_order_project_id // 新的分订单项目id
     *    *  @param string $type // 1 换技师 2 换项目
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 寻找项目技师
     */
    public function find_engineer($old_order_project_id, $project_id, $sex = '0', $new_order_project_id, $type, $startTime, $endTime)
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
        $oldorder = $this->where('id', $old_order_project_id)->find();
        $bigorder = Order::where('id', $oldorder['order_id'])->find();
        if (empty($oldorder)) {
            $result['msg'] = '原项目不存在';
            return $result;
        }
        $engineer_id = $oldorder['engineer_id'];
        $where = array();
        if ($type == '1') {
            $where[] = ['u.id', 'neq', $engineer_id];
        }
        if (!empty($sex)) {
            $where[] = ['u.sex', 'eq', $sex];
        }
        //查找当前项目的轮排技师id
        $newengineer = Db::name('qt_order_queue')
            ->alias('q')
            ->join('qt_users u', 'u.id=q.user_id', 'left')
            ->join('qt_user_project j', 'u.id=j.engineer_id', 'left')
            ->where('q.status', '1')
            ->field('q.id,q.user_id')
            ->where($where)
            ->where('j.project_id', $project_id)
            ->order('q.sort asc')
            ->find();
        if (empty($newengineer)) {
            $result['msg'] = '当前无可用技师';
            return $result;
        }
        //最新排序   旧的技师排最后
        $bigsort = Db::name('qt_order_queue')->max('sort');
        $bigsort = $bigsort + 1;
        $project = Project::where('id', $project_id)->find();
        if ($oldorder['order_type'] == '1') {
            $rale = $project['normal_rate'];
        } else if ($oldorder['order_type'] == '2') {
            //点钟
            $rale = $project['dot_block_rate'];
        } else if ($oldorder['order_type'] == '3') {
            //call 中
            $rale = $project['call_block_rate'];
        } else if ($oldorder['order_type'] == '4') {
            //优轮
            $rale = $project['call_block_rate'];
        } else if ($oldorder['order_type'] == '5') {
            //加钟
            $rale = $project['add_block_rate'];
        }
        Db::startTrans();
        try {
            //切换旧的技师排序
            Db::name('qt_order_queue')
                ->where('user_id', $engineer_id)
                ->where('order_project_id', $oldorder['id'])
                ->update(
                    [
                        'room_id' => '0',
                        'project_id' => '0',
                        'order_project_id' => '0',
                        'order_user_id' => '0',
                        'status' => '1',
                        'sort' => $bigsort,
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                    ]
                );
            //删除记录
            Db::name('qt_commission_log')
                ->where('order_project_id', $oldorder['id'])
                ->delete();
            //修改新的技师
            Db::name('qt_order_queue')->where('id', $newengineer['id'])->update(
                [
                    'room_id' => $oldorder['room_id'],
                    'project_id' => $project_id,
                    'order_project_id' => $new_order_project_id,
                    'order_user_id' => $bigorder['uv_id'],
                    'status' => '2',
                ]
            );
            //新增订单提成明细表
            $commion_log = array(
                'store_id' => $bigorder['store_id'],
                'user_id' => $engineer_id,
                //'cashier_id'=>$arr['saler_id'],
                'member' => $bigorder['uv_id'],
                'money' => $project['price'],
                'payment_price' => $project['price'],
                'commission' => $project['price'] * $rale / 100,
                'rale' => $rale,
                'product_id' => $project_id,
                'type' => '1',
                'pay_type' => '',
                'created_time' => time(),
                'room_id' => $bigorder['room_id'],
                'is_pay' => '1',
            );
            CommissionLog::create($commion_log);
            //修改分订单的技师id
            Db::name('qt_order_project')->where('id', $new_order_project_id)->update(
                [
                    'engineer_id' => $newengineer['user_id'],
                    'status' => '1',
                ]
            );
            Db::commit();
            $res = true;
        } catch (\Exception $e) {
            Db::rollback();
            $res = false;
        }
        if ($res) {
            $result['status'] = true;
            return $result;
        } else {
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }

    /**
     * @param int $store_id
     * @param $project_id
     * @param $room_id
     * @param string $sex
     * @param $engineer_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 换项目
     */
    public function change_project($store_id, $order_project_id, $room_id, $new_project_id)
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
        $old = $this
            ->where('id', $order_project_id)
            ->where('room_id', $room_id)
            ->where('store_id', $store_id)
            ->find();
        if (empty($old)) {
            $result['msg'] = '当前项目不存在';
            return $result;
        }

        if ($old['project_id'] == $new_project_id) {
            $result['msg'] = '更换项目与原项目一致';
            return $result;
        }

        if ($old['status'] != '1') {
            $result['msg'] = '当前项目已开始无法更换';
            return $result;
        }
        $new_project = Project::where('id', $new_project_id)->find();
        if (empty($new_project)) {
            $result['msg'] = '没有找到当前项目';
            return $result;
        }
        $project['order_id'] = $old['order_id'];
        $project['room_id'] = $room_id;
        $project['hand_card_id'] = $old['hand_card_id'];
        $project['order_type'] = '1';
        $project['status'] = $old['status'];
        $project['project_id'] = $new_project_id;
        $project['name'] = $new_project['name'];
        $project['price'] = $new_project['price'];
        $project['created_time'] = time();
        $project['store_id'] = $new_project['store_id'];
        $project['payment_price'] = $new_project['price'];
        $project['is_change'] = '3';
        $startTime = null;
        $endTime = null;
        if ($old['status'] == '2') {
            $project['start_time'] = $old['start_time'];
            $startTime = $old['start_time'];
            $projectTime = Db::name('qt_project')->where(['id' => $old['project_id']])->value('time');
            $endTime = time() + ($projectTime * 60);
            $project['end_time'] = $endTime;
        }

        Db::startTrans();
        try {
            Db::name('qt_order_project')->where('id', $order_project_id)->update(['status' => '5']);
            $neworder_project_id = Db::name('qt_order_project')->insertGetId($project);
            $l = $this->find_engineer($order_project_id, $new_project_id, '', $neworder_project_id, '2', $startTime, $endTime);
            if ($l['status']) {
                Db::commit();
                $res = true;
            } else {
                $result['msg'] = $l['msg'];
                return $result;
            }
        } catch (\Exception $e) {
            Db::rollback();
            $res = false;
        }
        if ($res) {
            $result['status'] = true;
            return $result;
        } else {
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }

    /**
     * 更新项目提成
     * @param $orderId
     */
    public static function commission_order($orderId){
        $orderData = Db::name('qt_order_project')->where(['id'=>$orderId])->find();
        //更新提成信息
        $project = Db::name('qt_project')->where('id', $orderData['project_id'])->find();
        $commission = 0;
        $isAdd = Db::name('qt_users')->where(['id'=>$orderData['engineer_id']])->value('is_add');
        //普通提成
        if ($isAdd == '1') {
            $commission = new OrdinaryService();
            $commission = $commission->showCommission('5', $isAdd, $project);
        }
        //加班提成
        if ($isAdd == '2') {
            $commission = new AddService();
            $commission = $commission->showCommission('5', $isAdd, $project);
        }
        //计算接待提成
        $receiver = new ReceiverService();
        $receiver = $receiver->showCommission('5', $isAdd, $project);
        $floor_commission_type = Db::name('qt_store')->where(['id'=>$orderData['store_id']])->value('floor_commission_type');
        if ($floor_commission_type == '1') {
            $cashierId = $orderData['created_order_id'];
        } else {
            $cashierId = $orderData['creater_room'];
        }
        $insert = [
            'store_id' => $orderData['store_id'],
            'cashier_id' => $cashierId,//接待人
            'user_id' => $orderData['engineer_id'],//技师
            'room_id' => $orderData['room_id'],
            'money' =>$project['add_block_price'],
            'commission' => $commission,//技师提成
            'receiver' => $receiver,//接待提成
            'product_id' => $orderData['project_id'],
            'type' => '1',
            'created_time' => time(),
            'is_pay' => '1',
            'order_project_id' => $orderId,
            'status' => '5',
            'is_add' => $isAdd,
        ];
        Db::name('qt_commission_log')->insert($insert);
        //更新订单提成
        Db::name('qt_order_project')->where(['id'=>$orderId])->update(['commission'=>$commission,'receiver'=>$receiver]);
    }

}